package com.muyu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.common.core.constant.Constants;
import com.muyu.common.core.constant.UserConstants;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.security.utils.SecurityUtils;
import com.muyu.common.system.domain.SysRole;
import com.muyu.common.system.domain.SysUser;
import com.muyu.system.domain.SysMenu;
import com.muyu.system.domain.model.SysMenuAddModel;
import com.muyu.system.domain.model.SysMenuListModel;
import com.muyu.system.domain.model.SysMenuUpdModel;
import com.muyu.system.domain.vo.MetaVo;
import com.muyu.system.domain.vo.RouterVo;
import com.muyu.system.domain.vo.TreeSelect;
import com.muyu.system.mapper.SysMenuMapper;
import com.muyu.system.mapper.SysRoleMapper;
import com.muyu.system.service.SysMenuService;
import com.muyu.system.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.muyu.common.core.constant.SplitConstants.COMMA_STR;

/**
 * 菜单 业务层处理
 *
 * @author muyu
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    public static final String PREMISSION_STRING = "perms[\"{0}\"]";

    private final SysMenuMapper menuMapper;

    private final SysRoleMapper roleMapper;

    private final SysRoleMenuService sysRoleMenuService;

    @Autowired
    public SysMenuServiceImpl(SysMenuMapper menuMapper, SysRoleMapper roleMapper, SysRoleMenuService sysRoleMenuService) {
        this.menuMapper = menuMapper;
        this.roleMapper = roleMapper;
        this.sysRoleMenuService = sysRoleMenuService;
    }

    /**
     * 根据用户查询系统菜单列表
     *
     * @param userId 用户ID
     *
     * @return 菜单列表
     */
    @Override
    public List<SysMenuListModel> selectMenuList (Long userId) {
        return selectMenuList(new SysMenuListModel(), userId);
    }

    /**
     * 查询系统菜单列表
     *
     * @param sysMenuListModel 菜单信息
     *
     * @return 菜单列表
     */
    @Override
    public List<SysMenuListModel> selectMenuList (SysMenuListModel sysMenuListModel, Long userId) {
        List<SysMenu> menuList = null;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.like(StringUtils.isNotBlank(sysMenuListModel.getMenuName()), SysMenu::getMenuName, sysMenuListModel.getMenuName());
            lambdaQueryWrapper.eq(StringUtils.isNotBlank(sysMenuListModel.getVisible()), SysMenu::getVisible, sysMenuListModel.getVisible());
            lambdaQueryWrapper.eq(StringUtils.isNotEmpty(sysMenuListModel.getStatus()), SysMenu::getStatus, sysMenuListModel.getStatus());
            lambdaQueryWrapper.orderByAsc(
                    SysMenu::getParentId, SysMenu::getOrderNum
            );
            menuList = this.list(lambdaQueryWrapper);
        } else {
            SysMenu menu = SysMenu.of(sysMenuListModel);
            menu.getParams().put("userId", userId);
            menuList = menuMapper.selectMenuListByUserId(menu);
        }

        return menuList.stream()
                .map(SysMenuListModel::buildSysMenuListModel)
                .toList();
    }

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     *
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByUserId (Long userId) {
        List<String> perms = menuMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(COMMA_STR)));
            }
        }
        return permsSet;
    }

    /**
     * 根据角色ID查询权限
     *
     * @param roleId 角色ID
     *
     * @return 权限列表
     */
    @Override
    public Set<String> selectMenuPermsByRoleId (Long roleId) {
        List<String> perms = menuMapper.selectMenuPermsByRoleId(roleId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StringUtils.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(COMMA_STR)));
            }
        }
        return permsSet;
    }

    /**
     * 根据用户ID查询菜单
     *
     * @param userId 用户名称
     *
     * @return 菜单列表
     */
    @Override
    public List<SysMenu> selectMenuTreeByUserId (Long userId) {
        List<SysMenu> menus = null;
        if (SecurityUtils.isAdmin(userId)) {
            menus = menuMapper.selectMenuTreeAll();
        } else {
            menus = menuMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, 0);
    }

    /**
     * 根据角色ID查询菜单树信息
     *
     * @param roleId 角色ID
     *
     * @return 选中菜单列表
     */
    @Override
    public List<Long> selectMenuListByRoleId (Long roleId) {
        SysRole role = roleMapper.selectRoleById(roleId);
        return menuMapper.selectMenuListByRoleId(roleId, role.isMenuCheckStrictly());
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     *
     * @return 路由列表
     */
    @Override
    public List<RouterVo> buildMenus (List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden("1".equals(menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(
                    MetaVo.builder()
                            .title(menu.getMenuName())
                            .icon(menu.getIcon())
                            .noCache(StringUtils.equals("1", menu.getIsCache()))
                            .link(StringUtils.ishttp(menu.getPath())? menu.getPath():null)
                            .build()
            );
            List<SysMenu> cMenus = menu.getChildren();
            if (StringUtils.isNotEmpty(cMenus) && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StringUtils.capitalize(menu.getPath()));
                children.setMeta(
                        MetaVo.builder()
                                .title(menu.getMenuName())
                                .icon(menu.getIcon())
                                .noCache(StringUtils.equals("1", menu.getIsCache()))
                                .link(StringUtils.ishttp(menu.getPath())? menu.getPath():null)
                                .build()
                );
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon()));
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setComponent(UserConstants.INNER_LINK);
                children.setName(StringUtils.capitalize(routerPath));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     *
     * @return 树结构列表
     */
    @Override
    public List<SysMenu> buildMenuTree (List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     *
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect (List<SysMenuListModel> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus.stream().map(SysMenu::buildSysMenu).collect(Collectors.toList()));
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据菜单ID查询信息
     *
     * @param menuId 菜单ID
     *
     * @return 菜单信息
     */
    @Override
    public SysMenu selectMenuById (Long menuId) {
        return this.getById(menuId);
    }

    /**
     * 是否存在菜单子节点
     *
     * @param menuId 菜单ID
     *
     * @return 结果
     */
    @Override
    public boolean hasChildByMenuId (Long menuId) {
        // select count(1)
        //        from sys_menu
        //        where parent_id = #{menuId}
        LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenu::getParentId, menuId);
        return this.count(lambdaQueryWrapper) > 0;
    }

    /**
     * 查询菜单使用数量
     *
     * @param menuId 菜单ID
     *
     * @return 结果
     */
    @Override
    public boolean checkMenuExistRole (Long menuId) {
        return sysRoleMenuService.checkMenuExistRole(menuId);
    }

    /**
     * 新增保存菜单信息
     *
     * @param sysMenuAddModel 菜单信息
     *
     * @return 结果
     */
    @Override
    public void insertMenu (SysMenuAddModel sysMenuAddModel) {
        SysMenu menu = SysMenu.buildSysMenu(sysMenuAddModel);
        this.save(menu);
    }

    /**
     * 修改保存菜单信息
     *
     * @param sysMenuUpdModel 菜单信息
     *
     * @return 结果
     */
    @Override
    public void updateMenu (SysMenuUpdModel sysMenuUpdModel) {
        this.updateById(SysMenu.buildSysMenu(sysMenuUpdModel));
    }

    /**
     * 删除菜单管理信息
     *
     * @param menuId 菜单ID
     *
     * @return 结果
     */
    @Override
    public void deleteMenuById (Long menuId) {
        this.removeById(menuId);
    }

    /**
     * 校验菜单名称是否唯一
     *
     * @param menuId 菜单ID
     * @param menuName 菜单名称
     *
     * @return 结果
     */
    @Override
    public boolean checkMenuNameUnique (Long menuId, String menuName) {
        LambdaQueryWrapper<SysMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysMenu::getMenuName, menuName);
        lambdaQueryWrapper.ne(menuId != null, SysMenu::getParentId, menuId);
        if (this.count(lambdaQueryWrapper) > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }



    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     *
     * @return 路由名称
     */
    public String getRouteName (SysMenu menu) {
        String routerName = StringUtils.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StringUtils.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     *
     * @return 路由地址
     */
    public String getRouterPath (SysMenu menu) {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && UserConstants.TYPE_DIR.equals(menu.getMenuType())
                && UserConstants.NO_FRAME.equals(menu.getIsFrame())) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     *
     * @return 组件信息
     */
    public String getComponent (SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StringUtils.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StringUtils.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu)) {
            component = UserConstants.INNER_LINK;
        } else if (StringUtils.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     *
     * @return 结果
     */
    public boolean isMenuFrame (SysMenu menu) {
        return menu.getParentId().intValue() == 0 && UserConstants.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(UserConstants.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     *
     * @return 结果
     */
    public boolean isInnerLink (SysMenu menu) {
        return menu.getIsFrame().equals(UserConstants.NO_FRAME) && StringUtils.ishttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     *
     * @return 结果
     */
    public boolean isParentView (SysMenu menu) {
        return menu.getParentId().intValue() != 0 && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list     分类表
     * @param parentId 传入的父节点ID
     *
     * @return String
     */
    public List<SysMenu> getChildPerms (List<SysMenu> list, int parentId) {
        List<SysMenu> returnList = new ArrayList<>();
        for (SysMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t    子节点
     */
    private void recursionFn (List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList (List<SysMenu> list, SysMenu t) {
        List<SysMenu> tlist = new ArrayList<>();
        for (SysMenu n : list) {
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild (List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    public String innerLinkReplaceEach (String path) {
        return StringUtils.replaceEach(path, new String[]{Constants.HTTP, Constants.HTTPS, Constants.WWW, ".", ":"},
                new String[]{"", "", "", "/", "/"});
    }
}
